//
//  LaunchAdvViewController.swift
//  koolcar
//
//  Created by feixiang huang on 2024/1/8.
//

import UIKit
import Reachability

class LaunchAdvViewController: UIViewController {
    var reachability: Reachability?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        _ = XTManageCenter.getAppleLanguages()
        self.checkNetworkState()
    }
    
    ///检测本地网络
    fileprivate func checkNetworkState() {
        reachability = try? Reachability()
        reachability?.whenReachable = { reach in
            switch reach.connection {
            case .wifi,
                    .cellular:
                self.reachability?.stopNotifier()
                self.requestBaseParameter() //去获取配置信息
            case .none:
                fallthrough
            default:
                print("Network not reachable")
            }
        }
        reachability?.whenUnreachable = { _ in
            let isFristOpen = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.isFristOpen)//是否引导页
            if isFristOpen != "" {
                self.enterSecondPage()
            }
        }
        do {
            try reachability?.startNotifier()
        } catch {
            print("Unable to start notifier")
        }
    }
 
    private func requestBaseParameter() {
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.baseParameter(param: ["":""]), objectType: BaseParameterModel.self) { data in
            let resultObj = data as! BaseParameterModel
            if resultObj.code == "1" && resultObj.data != nil {
                XTManageCenter.setLocalPlaceParameter(paramData: resultObj.data)
            }
            self.enterSecondPage()
        } error: { err in
            
        }
    }
    
    private func enterSecondPage(){
        let isFristOpen = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.isFristOpen)//是否引导页
        if isFristOpen == "" {
            //进入引导页
            let vc = GuidePageViewController()
            UIApplication.shared.keyWindow?.rootViewController = UINavigationController.init(rootViewController: vc)
        }else{
            let tabbarVC = BaseTabbarController()
            UIApplication.shared.keyWindow?.rootViewController = tabbarVC
            tabbarVC.selectedIndex = 0
        }
    }
    
}
